
const http = require("../../api/index")
const { baseURL } = require("../../utils/request")
Page({
  /**
   * 页面的初始数据
   */
  data: {
    oss_url: baseURL,
    score: "",
    content: "",
    fileList: [],
    campId: "",
    releaseTime: "",
    imageUrl: "",
    anonymous: "1",
    goodsId:"",
    userId: '', // 用户 ID
    
  },
  // 放弃编辑
  resetFiled() {
    this.setData({
      score: "",
      content: "",
      fileList: [],
      imageUrl: ""
    })
    //返回上一个页面
    wx.navigateBack({
      delta: 1
    });

  },
  // 上传完毕的回调函数
  afterRead(event) {
    wx.showLoading({
      title: '正在上传图片',
      mask: true
    })
    let that = this
    console.log(event, "图片上传event");
    const {
      file
    } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式
    const userInfo = wx.getStorageSync('userInfo') || null;
    // console.log(userInfo,"######");
    const token = userInfo.token
    // 批量上传文件
    const uploadPromises = file.map((f) => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'http://127.0.0.1:8080/common/upload', // 仅为示例，非真实的接口地址
          // url: 'http://127.0.0.1:8080/common/upload', // 仅为示例，非真实的接口地址
          filePath: f.url,
          name: 'file',
          header: {
            'Authorization': `Bearer ${token}`,
            'content-type': 'application/json',
          },
          success: (res) => {
            try {
              // 尝试解析响应数据
              const parsedData = JSON.parse(res.data);
              resolve(parsedData);
            } catch (parseError) {
              console.error('解析响应数据失败:', parseError);
              reject(parseError);
            }
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    });
    // 所有文件上传完成后更新 fileList 和 filenames 字符串
    Promise.all(uploadPromises).then((responses) => {
      const {
        fileList = []
      } = that.data;
      console.log(responses, "responses");
      // 确保 responses 是一个数组
      if (!Array.isArray(responses)) {
        throw new Error('responses is not an array');
      }
      const updatedFiles = responses.map((res, index) => ({
        url: res.url, // 上传后的文件 URL
      }));
      console.log(updatedFiles, "updatedFiles");
      // 更新 fileList
      fileList.push(...updatedFiles);
      that.setData({
        fileList
      });
      // 组合文件地址名
      const filenames = responses.map(res => res.fileName);
      const filenamesString = filenames.join(',');
      // 更新 filenamesString
      that.setData({
        imageUrl: filenamesString
      });
      console.log(that.data, "data");
      wx.hideLoading()

    }).catch((error) => {
      console.error('上传文件失败:', error);
    });
  },
  //删除
  delete(e) {
    const index = e.detail.index
    this.setData({
      fileList: this.data.fileList.splice(1, index)
    })
  },
  //提交评价
  submitComment() {
    // 验证关键字段是否已填写
    const { goodsId, userId, score, content, fileList } = this.data;
    if (!goodsId || !userId || !score || !content) {
      wx.showToast({
        title: '请填写所有必填项。',
        icon: "none",
      });
      return;
    }
    // 构建上传数据对象，并将 goodsId 映射为 goodsid
    const submitData = {
      goodsId: goodsId,
      userId: userId,
      score: score,
      content: content,
      fileList: fileList.map(file => file.url),
      anonymous: this.data.anonymous,
      imageUrl: this.data.imageUrl,
    };
    
    console.log('Submitting data:', submitData); // 开发环境下的日志
    http.addValuation(submitData)
      .then(res => {
        console.log('API response:', res); // 打印完整的 API 响应
        
        if (res.code === 200) {
          wx.showToast({
            title: '提交成功！',
            icon: "success",
          });
          setTimeout(() => {
            // 返回上一个页面
            wx.navigateBack({ delta: 1 });
          }, 1500); // 增加一点时间让用户看到成功提示
        } else {
          wx.showToast({
            title: '提交失败，请重试。',
            icon: "none",
          });
          console.error('Submit failed with code:', res.code, 'and message:', res.msg);
        }
      })
      .catch(err => {
        wx.showToast({
          title: '提交失败，',
          icon: "none",
        });
        console.error('Error during submission:', err);
        console.log('Full error object:', err); // 打印完整的错误对象
      });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('Received options:', options);
    const userInfo = wx.getStorageSync("userInfo")
    this.setData({
      goodsId: options.goodsId, 
      userId: userInfo.userId
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})